package com.greate.shiro.springbootshirodemo.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.greate.shiro.springbootshirodemo.common.Constants;
import com.greate.shiro.springbootshirodemo.entity.SystemRole;
import com.greate.shiro.springbootshirodemo.entity.SystemUser;
import com.greate.shiro.springbootshirodemo.entity.SystemUserRole;
import com.greate.shiro.springbootshirodemo.mapper.SystemRoleMapper;
import com.greate.shiro.springbootshirodemo.mapper.SystemUserMapper;
import com.greate.shiro.springbootshirodemo.mapper.SystemUserRoleMapper;
import com.greate.shiro.springbootshirodemo.service.SystemUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import static com.greate.shiro.springbootshirodemo.utils.MybatisPlusUtils.lQuery;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zs
 * @since 2020-07-28
 */
@Service
public class SystemUserServiceImpl extends ServiceImpl<SystemUserMapper, SystemUser> implements SystemUserService {

	@Resource
	private SystemUserRoleMapper systemUserRoleMapper;

	@Resource
	private SystemRoleMapper systemRoleMapper;

	@Override
	public List<String> getRolesNameStringList(String username, String password) {

		// 得到用户的id
		Integer id = lambdaQuery()
			.eq(SystemUser::getUsername, username)
			.eq(SystemUser::getPassword, password)
			.last(Constants.Sql.LIMIT_ONE)
			.one().getId();

		// 查询用户拥有的角色 id（所有的角色id）
		List<Integer> roleIds = lQuery(systemUserRoleMapper)
			.eq(SystemUserRole::getUserId, id)
			.list()
			.stream()
			.map(SystemUserRole::getRoleId)
			.collect(Collectors.toList());

		// 根据角色的id查询所有的角色的名字
		return lQuery(systemRoleMapper)
			.in(SystemRole::getId, roleIds)
			.list()
			.stream()
			.map(SystemRole::getRoleName)
			.collect(Collectors.toList());
	}

	@Override
	public Integer getUserIdByUsernameAndPassword(String username, String password) {
		return lambdaQuery()
			.eq(SystemUser::getUsername, username)
			.eq(SystemUser::getPassword, password)
			.last(Constants.Sql.LIMIT_ONE)
			.one().getId();
	}


}
